package com.sunpy.niohttp.file;

import com.sunpy.niohttp.model.ConfigInfo;
import org.springframework.util.ResourceUtils;
import java.io.*;
import java.util.Properties;

public class HttpPropertiesConfig {

    /**
     * properties文件默认名称
     */
    private static final String PROP_NAME ="nio-http.properties";

    private static final String PROP_PATH_PREFIX = "classpath:";

    private static final String PROP_PATH_ROOT_PREFIX = "classpath*:";

    /**
     * 默认加载resources文件下配置的nio-http.properties
     * @return
     */
    public static Properties getProperties() {
        /**
         * 在classpath*路径下查找nio-http.properties文件
         */
        Properties properties = new Properties();
        InputStream is = null;
        FileInputStream fis = null;

        try {
            is = ClassLoader.getSystemResourceAsStream(PROP_NAME);

            if (is == null) {
                File file = ResourceUtils.getFile(PROP_PATH_ROOT_PREFIX + PROP_NAME);

                if (file == null) {
                    return null;
                }

                fis = new FileInputStream(file);
                properties.load(fis);

                return properties;
            }

            properties.load(is);
            return properties;
        } catch (FileNotFoundException e) {
           e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (is != null) {
                    is.close();
                }

                if (fis != null) {
                    fis.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }

        return null;
    }

    public static ConfigInfo getConfig() {
        Properties props = getProperties();
        ConfigInfo configInfo = new ConfigInfo(props.getProperty("server_name"),
                props.getProperty("server_ip"),
                Integer.parseInt(props.getProperty("server_port")));

        return configInfo;
    }

    public static String getUserPackage() {
        Properties props = getProperties();
        return props.getProperty("user_package");
    }

}
